
var express = require('express');

const xlsx = require("node-xlsx").default;
var router = express.Router();
const { UserModule } = require('../mongodb/db')
const sendVerificationCode = require('../module/sendVerificationCode')
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


router.get('/list', async (req, res) => {
  let data = await UserModule.find()
  console.log(data);
  res.send({
    code: 200,
    msg: '成功',
    data
  })
})


function generateCode() {
  return Math.floor(100000 + Math.random() * 900000).toString();
}


router.post('/number', async (req, res) => {
  let phone = req.body.phoneNumber
  let code = generateCode();
  try {
    // 发送短信
    await sendVerificationCode(phone, code);

    // 保存验证码到用户文档（实际项目中可以使用 Redis 存储验证码）
    // let user = await UserModule.findOne({ phone });
    res.send({ code: 200 })
  } catch (error) {
    console.log('报错');

  }
})
router.post('/verify', async (req, res) => {
  const { verificationCode } = req.body
  try {
    if (verificationCode === '') {
      res.send({ code: 200 })
    } else {
      res.send({ code: 404 })
    }
  } catch (error) {
    console.log('报错');

  }
})


const multiparty = require('multiparty')
const fs = require('fs')
// router.post('/file',async (req,res)=>{
//   const form = new multiparty.Form()
//   form.uploadDir = 'files'
//   form.parse(req,(error,fields,files)=>{
//   const dataXlsx = xlsx.parse(fs.readFileSync(files.file[0].path))
//   let datas = dataXlsx[0].data
//   const headers = datas[0]
//   datas.splice(0,1)
//   let data = []
//   datas.forEach(row => {
//     let entry = {};
//     headers.forEach((header, index) => {
//         entry[header] = row[index]; 
//     });
//     data.push(entry);
//   });
//   console.log(data);
//    res.send({
//     code:200,
//     msg:'成功',
//     fileUrl:'http://localhost:3000/'+files.file[0].path
//   })
//   })
// })


// router.post('/image',async (req,res)=>{
//   const form = new multiparty.Form()
//   form.uploadDir = 'upload'
//   form.parse(req,(error,fields,files)=>{
//     res.send({
//           code:200,
//           msg:'成功',
//           fileUrl:'http://localhost:3000/'+files.file[0].path
//         })
//   }
// )
// })




module.exports = router;